package com.fuda.trade

import android.app.Application
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.icu.text.SimpleDateFormat
import android.util.Log
import com.fuda.trade.TradeAccessibilityService.Companion
import com.fuda.trade.party3.cczq.CczqAppHandler
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit

class MyApplication: Application() {
    companion object {
        val TAG: String = MyApplication::class.java.simpleName

        lateinit var zenohManager: ZenohManager
        lateinit var party3AppManager: Party3AppManager

    }


    override fun onCreate() {
        super.onCreate()
        zenohManager = ZenohManager()
        party3AppManager = Party3AppManager(CczqAppHandler())
        // commandManager = Party3AppManager(GuosenAppHandler())
        // commandManager = Party3AppManager(CczqAppHandler())
    }
}


fun logElapsedTime(tag:String, startTime: Long  ) {
    val endTime = System.currentTimeMillis()

    val elapsedMillis = endTime - startTime
    val elapsedSeconds = elapsedMillis / 1000
    val elapsedMillisRemaining = elapsedMillis % 1000

    // Format the start and end times
    val sdf = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())
    val startDate = Date(startTime)
    val endDate = Date(endTime)

    Log.e(tag, "start: ${sdf.format(startDate)} end: ${sdf.format(endDate)} time: ${elapsedSeconds}s${elapsedMillisRemaining}ms")
}


// party3 app ui operators
fun startParty3App(context: Context, packageName: String, className: String) :Boolean{
    var result  = false
    Log.i(TradeAccessibilityService.TAG, "(startParty3App) startThirdPartyApp($packageName, $className)")

    if (!isAppInstalled(context,packageName)) {
        Log.e(TradeAccessibilityService.TAG, "(startParty3App) The app with package $packageName is not installed.")
        result = false
    }else {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        intent.setClassName(packageName, className)
        // Add the necessary intent flags
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED or Intent.FLAG_ACTIVITY_CLEAR_TOP)

        try {
            // Use getApplicationContext() to start the activity from the AccessibilityService
            context.startActivity(intent)
            result = true
        } catch (e: ActivityNotFoundException) {
            // Handle the case where the app is not installed
            Log.e(TradeAccessibilityService.TAG, "(startParty3App) Failed to start party3 app: $e")
        }
    }
    return result
}


private fun isAppInstalled(context:Context, packageName: String): Boolean {
    val pm = context.packageManager
    try {
        pm.getPackageInfo(packageName, 0)
        return true
    } catch (e: PackageManager.NameNotFoundException) {
        return false
    }
}


fun startMainActivity(context: Context) {
    TimeUnit.SECONDS.sleep(1)
    TimeUnit.SECONDS.sleep(2)
    try {
        // Get the application context from the service

        // Create an Intent to start MainActivity
        val intent = Intent(context, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)

        // Start the activity
        context.startActivity(intent)
    } catch (e: Exception) {
        Log.e(Companion.TAG, "(startMainActivity) Failed to start MainActivity", e)
    }
}
